<template>
    <el-dialog :close-on-click-modal="false"  ref="dialogform" :title="addEditName + title" :visible.sync="dialogVisible" width="40%"
        :before-close="handleClose">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
            <el-form-item label="养殖设施" prop="facilityId">
                <el-select v-if="addEditFlag=='add'" v-model="ruleForm.facilityId" class="w100p" placeholder="请选择养殖设施" @change="getFacilityName">
                    <el-option v-for="(item, index) in facilityList" :key="index" :label="item.facilityName"
                        :value="item.facilityId" />
                </el-select>
                <el-input v-if="addEditFlag=='edit'" disabled v-model="ruleForm.facilityName"></el-input>
            </el-form-item>
            <el-form-item label="选择批次" prop="batchId">
                <el-select v-if="addEditFlag=='add'"  v-model="ruleForm.batchId" class="w100p" placeholder="请选择批次" @change="getBatchName">
                    <el-option v-if="ruleForm.facilityId == item.facilityId && item.status == 'SEALED_POND'"
                        v-for="(item, index) in batchList" :key="index" :value="item.batchId" :label="item.batchName" />
                </el-select>
                <el-input v-if="addEditFlag=='edit'" disabled v-model="ruleForm.batchName"></el-input>
            </el-form-item>
            <el-form-item label="选择品种" prop="plantVarietyId">
                <el-select v-if="addEditFlag=='add'"  v-model="ruleForm.plantVarietyId" class="w100p" filterable placeholder="请选择养殖品种"
                    @change="handleChangePlantVariety">
                    <el-option v-if="plantVarietyIdList.includes(v.plantVarietyId)" v-for="v, index in varietyList"
                        :key="index" :label="v.plantVarietyName" :value="v.plantVarietyId"></el-option>
                    <!-- <el-option v-for="item, index in varietyList" :key="index" :label="item.plantVarietyName"
                        :value="item.plantVarietyId"></el-option> -->
                </el-select>
                <el-input v-if="addEditFlag=='edit'" disabled v-model="ruleForm.plantVarietyName"></el-input>
            </el-form-item>
            <el-form-item label="死亡数量" prop="num">
                <el-input type="number" v-model="ruleForm.num" placeholder="请输入数量"></el-input>
            </el-form-item>
            <el-form-item label="死亡重量" prop="weight">
                <el-input type="number" v-model="ruleForm.weight" placeholder="请输入重量">
                    <template slot="append">斤</template>
                </el-input>
            </el-form-item>
            <el-form-item label="发现人" prop="staffId">
                <el-select v-model="ruleForm.staffId" class="w100p" placeholder="请选择操作人" @change="handleChangePerson">
                    <el-option v-for="item, index in person" :key="index" :label="item.person.name"
                        :value="item.person.personNo"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="发现死亡日期" prop="deadDate">
                <el-date-picker v-model="ruleForm.deadDate" value-format="yyyy-MM-dd" align="right" type="date" placeholder="选择日期"
                    :picker-options="pickerOptions">
                </el-date-picker>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="cancel">取 消</el-button>
            <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
    </el-dialog>
</template>

<script>
import straightFishRecord from '@/api/healthManagement/straightFishRecord.js';
import batch from '@/api/batch/batchManagement';
export default {
    components: {},
    props: {
        addEditFlag: {
            type: String,
            default: () => {
                return 'add'
            }
        },
        data: {
            type: Object,
            default: () => {
                return {}
            }
        },
        title: {
            type: String,
            default: () => {
                return '操作表单'
            }
        },
        dialogVisible: {
            type: Boolean,
            default: () => {
                return false
            }
        },
        batchList: {
            type: Array,
            default: () => {
                return false
            }
        },
        varietyList: {
            type: Array,
            default: () => {
                return false
            }
        },
        facilityList: {
            type: Array,
            default: () => {
                return false
            }
        },
    },
    data() {
        let validatorNumber = function (rule, value, callback) {
            if (value > 0) {
                callback()
            } else {
                callback(new Error('请输入大于0的数值！'))
            }
        }
        let validatorNumber_integer = function (rule, value, callback) {
            if (value > 0 && value % 1 == 0) {
                callback()
            } else {
                callback(new Error('请输入大于0的整数！'))
            }
        }
        return {
            pickerOptions: {
                disabledDate(time) {
                    return time.getTime() > Date.now();
                },
                shortcuts: [{
                    text: '今天',
                    onClick(picker) {
                        picker.$emit('pick', new Date());
                    }
                }, {
                    text: '昨天',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() - 3600 * 1000 * 24);
                        picker.$emit('pick', date);
                    }
                }, {
                    text: '一周前',
                    onClick(picker) {
                        const date = new Date();
                        date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
                        picker.$emit('pick', date);
                    }
                }]
            },
            plantVarietyIdList: [],
            addEditName: '添加',
            addEditApi: '',
            ruleForm: {},
            rules: {
                facilityId: [
                    { required: true, message: '请选择养殖设施', trigger: 'change' }
                ],
                batchId: [
                    { required: true, message: '请选择批次', trigger: 'change' }
                ],
                plantVarietyId: [
                    { required: true, message: '请选择品种', trigger: 'change' }
                ],
                num: [
                    { required: true, validator: validatorNumber_integer, trigger: 'change' }
                ],
                weight: [
                    { required: true, validator: validatorNumber, trigger: 'change' }
                ],
                staffId: [
                    { required: true, message: '请选择发现人', trigger: 'change' }
                ],
                deadDate: [
                    { required: true, message: '请选择日期', trigger: 'change' }
                ]
            }
        }
    },

    computed: {
        person() {
            return this.$store.state.initData.person || [];
        },
    },
    watch: {
        dialogVisible(v) {
            v && this.initData()
        }
    },

    mounted() { },
    methods: {
        initData() {
            if (this.addEditFlag == 'add') {
                this.resetForm()
                this.ruleForm = {}
                this.addEditApi = straightFishRecord.add
                this.addEditName = '添加'
            } else if (this.addEditFlag == 'edit') {
                this.ruleForm = {
                    ...this.data,
                    staffId: this.data.personNo||this.data.staffId
                }
                this.addEditApi = straightFishRecord.edit
                this.addEditName = '编辑'
                this.queryByConditionPondInfo(this.data.batchId)
            }
        },

        getBatchName() {
            let result = this.batchList.find(obj => obj.batchId == this.ruleForm.batchId);
            this.$set(this.ruleForm, 'batchName', result.batchName);
            this.queryByConditionPondInfo(this.ruleForm.batchId)
        },
        getFacilityName() {
            let result = this.facilityList.find(obj => obj.facilityId == this.ruleForm.facilityId);
            console.log(result)
            this.$set(this.ruleForm, 'facilityName', result.facilityName || "");
            this.$set(this.ruleForm, 'batchId', '');
            this.$set(this.ruleForm, 'batchName', '');
        },
        handleChangePlantVariety(e) {
            let result = this.varietyList.find(obj => obj.plantVarietyId == e);
            this.$set(this.ruleForm, 'plantVarietyName', result.plantVarietyName)
        },

        handleChangePerson(id) {
            let row = this.person.find(item => Number(item.person.personNo) == id);
            this.$set(this.ruleForm, 'staffName', row.person.name);
        },
        async queryByConditionPondInfo(id) {
            this.plantVarietyIdList = [];
            if (!id) return;
            try {
                const res = await batch.queryByConditionBatchPond({ batchId: id });
                // 检查返回的状态码  
                if (res.code !== 1 && !res.data) {
                    return; // 如果状态码不是1，直接返回并不做后续处理  
                }
                let inputPondDetailList = res.data || [];
                console.log(inputPondDetailList)
                // 如果inputPondDetailList存在且有数据，则处理数据  
                if (inputPondDetailList.length > 0) {
                    this.plantVarietyIdList = inputPondDetailList.map(item => item.plantVarietyId);
                } else {
                    this.$message.warning('请重新选择批次，该批次无投塘数据！')
                }
                console.log(this.plantVarietyIdList)
            } catch (error) {
                console.log(error);
            }
        },
        //提交表单
        submitForm() {
            this.$refs.ruleForm.validate((valid) => {
                if (valid) {
                    this.addEditApi({ ...this.ruleForm }).then(res => {
                        this.$message[res.code == 1 ? 'success' : 'warning'](res.code == 1 ? '操作成功' : res.msg)
                        res.code == 1 && this.cancel();
                    }).catch(err => {
                        console.log(err)
                    })
                } else {
                    return false;
                }
            })
        },
        //重置
        resetForm() {
            this.ruleForm = {};
            this.$refs.ruleForm && this.$refs.ruleForm.resetFields()
        },
        //取消关闭
        cancel() {
            this.resetForm()
            this.$emit("closeDialog")
        },
        handleClose(done) {
            this.$confirm('确认关闭？')
                .then(_ => { this.resetForm(); this.cancel() })
                .catch(_ => { });
        }
    }
};
</script>

<style lang="scss" scoped></style>